package com.onepiece.requestproxy.util;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.onepiece.requestproxy.util.ReflectHelper;

/**
 * 解析XML文件 对应规则 _a转成A
 * 
 * @author JueYue 2014年2月19日--下午5:03:05
 */
@SuppressWarnings("unchecked")
public class XMLParseUtil {
	
	
	private static final Logger logger = LoggerFactory.getLogger(XMLParseUtil.class);

	/**
	 * 获取实体类
	 * 
	 * @date 2014年2月19日
	 * @param xml
	 * @param clazz
	 * @return
	 */
	public static <T> T getEntity(String xml, Class<?> clazz) {
		Object obj = null;
		xml = xml.trim();
		if(logger.isDebugEnabled())
			logger.debug("XML内容:"+xml);
		try {
			obj = clazz.newInstance();
			ReflectHelper helper = new ReflectHelper(obj);
			Document document = null;
			SAXReader saxReader = new SAXReader();
			saxReader.setEncoding("UTF-8");
			try {
				document = saxReader.read(new ByteArrayInputStream(xml.getBytes("utf-8")));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			Element root = document.getRootElement();
			List<Element> beans = root.elements();
			boolean isSetOk;
			for (Element bean : beans) {
				isSetOk = helper.setMethodValue(getRealName(bean.getName()),
						getText(bean.getText()));
				if (!isSetOk) {
					helper.setMethodValue(bean.getName(), getText(bean.getText()));
				}
			}
		}catch (Exception e){
			e.printStackTrace();
			throw new RuntimeException("XML解析异常");
		}
		return (T) obj;
	}
	
	private static String getText(String text) {
		return text.replaceAll("\\n\\t", "");
	}

	private static String getRealName(String name) {
		StringBuffer realName = new StringBuffer();
		char[] chars = name.toCharArray();
		for (int i = 0, le = chars.length; i < le; i++) {
			if (chars[i] == '_') {
				i++;
				realName.append(Character.toUpperCase(chars[i]));
			} else {
				realName.append(chars[i]);
			}
		}
		return realName.toString();
	}

}
